package com.justonw.solution;

import java.util.PriorityQueue;

/**
 * 从n个数中找到，最大的k个数
 */
public class Solution2_1 {
    public int findkthBig(int[] array, int k) {
        //如果当前数组的长度小于或者等于k，直接返回就可以了
        PriorityQueue<Integer> minHead = new PriorityQueue<>(k);
        for (int i = 0; i < array.length; i++) {
            if (minHead.size() < k) {
                minHead.offer(array[i]);
            } else if (minHead.peek() < array[i]){
                //大于小顶堆中堆顶元素后，将堆顶元素删除，然后将
                minHead.poll();
                minHead.offer(array[i]);
            }
        }
        return minHead.peek();
    }

    public static void main(String[] args) {
        int[] array = {1, 5, 6, 2, 3,7,8};
        int k = 2;
        Solution2_1 solution2_1 = new Solution2_1();
        int i = solution2_1.findkthBig(array, k);
        System.out.println(i);
    }
}
